﻿using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.JSInterop;
using MudBlazor;
using Newtonsoft.Json.Linq;
using Plotly.Blazor;
using Plotly.Blazor.Interop;
using Plotly.Blazor.LayoutLib;
using Plotly.Blazor.Traces;
using Plotly.Blazor.Traces.ScatterLib;
using System.Text.Json;
using static BlazorSample.Pages.TreeTest;

namespace BlazorSample.Pages
{
    public partial class PlotlyBlazorLineChartTest
    {
        private PlotlyChart plotlyChart;
        private Config config;
        private Plotly.Blazor.Layout layout;
        private IList<ITrace> data;
        private RelayoutEventData relayoutData;
        private RestyleEventData restyleData;

        public PlotlyBlazorLineChartTest()
        {

        }

        private List<object> XAxisRange { get; set; } = new List<object> { 1, 4 };

        private async Task AddData()
        {
            var count = 500;
            if (!(plotlyChart.Data.FirstOrDefault() is Scatter scatter)) return;
            var (x, y) = Helper.GenerateData(scatter.X.Count + 1, scatter.X.Count + 1 + count);
            XAxisRange = new List<object>();
            XAxisRange.Add(x.Min(s => s));
            XAxisRange.Add(x.Max(s => s));
            await plotlyChart.ExtendTrace(x, y, data.IndexOf(scatter));

            layout.XAxis[0].Range = XAxisRange;
            base.StateHasChanged();
        }

        private async void Init()
        {
            await plotlyChart.SubscribeRelayoutEvent();
            await plotlyChart.SubscribeRestyleEvent();
        }

        public async void SelectedAction(IEnumerable<EventDataPoint> eventData)
        {
        }

        public async void RelayoutAction(RelayoutEventData eventData)
        {
            relayoutData = eventData;
            var rData = eventData.RawData.FirstOrDefault();
            var firstKey = rData.Key;

            if (firstKey.StartsWith("selections["))
            {
                var match = System.Text.RegularExpressions.Regex.Match(firstKey, @"\[(\d+)\]");// 使用正则提取索引
                if (match.Success)
                {
                    int index = int.Parse(match.Groups[1].Value);
                    var movedShape = layout.Selections[index];

                    double targetX0 = eventData.RawData.TryGetValue($"selections[{index}].x0", out var x0) ? Convert.ToDouble(x0.ToString()) : Convert.ToDouble(movedShape.X0);
                    double targetX1 = eventData.RawData.TryGetValue($"selections[{index}].x1", out var x1) ? Convert.ToDouble(x1.ToString()) : Convert.ToDouble(movedShape.X1);

                    movedShape.X0 = targetX0;
                    movedShape.X1 = targetX1;
                    movedShape.Y0 = 0;
                    movedShape.Y1 = 1;

                    //await plotlyChart.React();
                    //await plotlyChart.Update(layoutUpdate: layout);


                    // 通过 Relayout 更新形状坐标
                    await plotlyChart.Relayout(new { shapes = movedShape });
                }
            }

            //if (firstKey.StartsWith("shapes["))
            //{
            //    var match = System.Text.RegularExpressions.Regex.Match(firstKey, @"\[(\d+)\]");// 使用正则提取索引
            //    if (match.Success)
            //    {
            //        int index = int.Parse(match.Groups[1].Value);
            //        var movedShape = layout.Shapes[index];

            //        double targetX0 = eventData.RawData.TryGetValue($"shapes[{index}].x0", out var x0) ? Convert.ToDouble(x0.ToString()) : Convert.ToDouble(movedShape.X0);
            //        double targetX1 = eventData.RawData.TryGetValue($"shapes[{index}].x1", out var x1) ? Convert.ToDouble(x1.ToString()) : Convert.ToDouble(movedShape.X1);

            //        movedShape.X0 = targetX0;
            //        movedShape.X1 = targetX1;
            //        movedShape.Y0 = 0;
            //        movedShape.Y1 = 1;

            //        await plotlyChart.React();
            //    }
            //    // 通过 Relayout 更新形状坐标
            //    //await plotlyChart.Relayout(new { shapes = layout.Shapes });
            //}

            if (firstKey.StartsWith("shapes["))
            {
                var match = System.Text.RegularExpressions.Regex.Match(firstKey, @"\[(\d+)\]");// 使用正则提取索引
                if (match.Success)
                {
                    int index = int.Parse(match.Groups[1].Value);
                    var movedShape = layout.Shapes[index];

                    double targetX0 = eventData.RawData.TryGetValue($"shapes[{index}].x0", out var x0) ? Convert.ToDouble(x0.ToString()) : Convert.ToDouble(movedShape.X0);
                    double targetX1 = eventData.RawData.TryGetValue($"shapes[{index}].x1", out var x1) ? Convert.ToDouble(x1.ToString()) : Convert.ToDouble(movedShape.X1);

                    movedShape.X0 = (int)targetX0;
                    movedShape.X1 = (int)targetX1;
                    movedShape.Y0 = 0;
                    movedShape.Y1 = 1;

                    // 通过字典更新布局
                    var updateDict = new Dictionary<string, object>
                    {
                        { "shapes", layout.Shapes }
                    };

                    // 强制更新图表
                    await plotlyChart.Update(layoutUpdate: layout);
                    //Init();
                    //await plotlyChart.React();
                    //plotlyChart.RelayoutAction += RelayoutAction;
                }
            }

            base.StateHasChanged();
            //await plotlyChart.Update(layoutUpdate: layout);
            //await plotlyChart.Relayout(new Dictionary<string, object>
            //{
            //    { "shapes[0].x0", 1 },
            //    { "shapes[0].x1", 3 },
            //    { "shapes[0].y0", 0 },
            //    { "shapes[0].y1", 1 }
            //});
            //foreach (var item in relayoutData.RawData)
            //{
            //    var value = item.Value.ToString();
            //    if (item.Key == "shapes[0].y0")
            //    {
            //        relayoutData.RawData["shapes[0].y0"] = JsonDocument.Parse("0").RootElement;
            //    }
            //    if (item.Key == "shapes[0].y1")
            //    {
            //        relayoutData.RawData["shapes[0].y1"] = JsonDocument.Parse("1").RootElement;
            //    }
            //}
        }

        public void RestyleAction(RestyleEventData eventData)
        {
            restyleData = eventData;
        }
    }
}
